package com.abe.libfitness.base;


import android.app.Dialog;
import android.content.Context;
import android.os.Bundle;
import android.util.DisplayMetrics;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;

import androidx.annotation.NonNull;

import com.abe.libcore.base.screen.RelayoutTool;
import com.abe.libcore.utils.CommonUtils;


public abstract class BaseScreenDialog extends Dialog {
    //是否正常设置标准宽度
    private Boolean isScreenSetNormal = false;

    public BaseScreenDialog(@NonNull Context context) {
        super(context);
    }

    //是否需要自适应布局
    protected abstract Boolean isAutoZoom();

    protected abstract int getLayoutRes();

    protected abstract void initContent();

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(getLayoutRes());
        initContent();
    }

    //获取标准宽度
    protected int getStandardW() {
        Integer designWidth = (Integer) CommonUtils.INSTANCE.getMetaData(getContext(), "designWidth", 0);
        isScreenSetNormal = designWidth != null;
        return isScreenSetNormal ? designWidth : 0;
    }

    //获取缩放比例
    protected Float getScale() {
        DisplayMetrics displayMetrics = getContext().getResources().getDisplayMetrics();
        int width = displayMetrics.widthPixels;
        int designWidth = getStandardW();
        return (isAutoZoom() && isScreenSetNormal) ? ((float) width / (float) designWidth) : 1.0F;
    }

    @Override
    public void setContentView(int layoutResID) {
        View view = View.inflate(getContext(), layoutResID, null);
        this.setContentView(view);
    }

    @Override
    public void setContentView(@NonNull View view) {
        RelayoutTool.INSTANCE.relayoutViewHierarchy(view, getScale());
        super.setContentView(view);
    }

    @Override
    public void show() {
        super.show();
        Window dialogWindow = getWindow();
        if (dialogWindow == null) return;
        WindowManager.LayoutParams lp = dialogWindow.getAttributes();
        DisplayMetrics d = getContext().getResources().getDisplayMetrics(); // 获取屏幕宽、高用
        lp.width = (int) (d.widthPixels * 0.85); // 宽度设置为屏幕的0.8
        dialogWindow.setAttributes(lp);
    }
}